package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.furongji.common.exception.MyException;
import com.furongji.common.utils.JwtUtil;
import com.furongji.education.domain.dto.UserDto;
import com.furongji.education.domain.po.User;
import com.furongji.education.mapper.UserMapper;
import com.furongji.education.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-05-25
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final RedisTemplate<String, Object> redisTemplate;

    private final UserMapper userMapper;

    @Override
    public String login(User user) {
        String username = user.getUsername();
        String password = DigestUtils.md5Hex(user.getPassword());

        System.err.println(username + ": " + password);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new MyException(20001, "登录失败");
        }

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUsername, username);
        User selectUser = super.getOne(userWrapper);

        if (selectUser == null) {
            throw new MyException(20001, "账户不存在");
        }

        if (selectUser.getIsDisabled()) {
            throw new MyException(20001, "该账户被禁用");
        }

        if (!password.equals(selectUser.getPassword())) {
            throw new MyException(20001, "密码错误");
        }

        String token = JwtUtil.createToken(selectUser.getId(), selectUser.getUsername());
        return token;
    }

    @Override
    public String loginEmail(UserDto userDto) {
        String email = userDto.getEmail();
        String code = userDto.getCode();

        if (!(StringUtils.hasText(email) || StringUtils.hasText(code))) {
            throw new MyException(20001, "登录失败");
        }

        String cacheEmailCode = (String) redisTemplate.opsForValue().get(userDto.getEmail());
        if (!code.equals(cacheEmailCode)) {
            throw new MyException(20001, "验证码错误");
        }

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getEmail, email);
        User selectUser = super.getOne(userWrapper);

        if (selectUser == null) {
            throw new MyException(20001, "账户不存在");
        }

        if (selectUser.getIsDisabled()) {
            throw new MyException(20001, "该账户被禁用");
        }

        String token = JwtUtil.createToken(selectUser.getId(), selectUser.getUsername());
        return token;
    }

    @Override
    public String register(UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        String email = userDto.getEmail();
        String code = userDto.getCode();

        if (!(StringUtils.hasText(username) ||
                StringUtils.hasText(password) ||
                StringUtils.hasText(email) || StringUtils.hasText(code))) {
            throw new MyException(20001, "注册失败");
        }

        String cacheEmailCode = (String) redisTemplate.opsForValue().get(userDto.getEmail());
        if (!code.equals(cacheEmailCode)) {
            throw new MyException(20001, "验证码错误");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        long userCount = super.count(wrapper);
        if (userCount > 0) {
            throw new MyException(20001, "用户名已被使用");
        }

        wrapper.clear();

        wrapper.eq(User::getEmail, email);
        long emailCount = super.count(wrapper);
        if (emailCount > 0) {
            throw new MyException(20001, "邮箱已被使用");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setEmail(email);
        user.setAvatar("https://ts1.tc.mm.bing.net/th/id/R-C.df6269351a36ffc54ed095d5b60ee691?rik=" +
                "WvUAdGmUWkfIvA&riu=http%3a%2f%2fupload.qianlong.com%2f2015%2f1019%2f1445217816710" +
                ".jpg&ehk=we%2ftSB1jcNyFyrIVBhA7qelOGmnHaeF6HH7nZZ8ITHM%3d&risl=&pid=ImgRaw&r=0");
        super.save(user);

        String token = JwtUtil.createToken(user.getId(), user.getUsername());
        return token;
    }

    @Override
    public User getUserInfo(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Claims claims = JwtUtil.parseToken(token);
        String userId = claims.get("userId", String.class);
        User user = super.getById(userId);
        return user;
    }

    @Override
    public Integer registerCount(String date) {
        Integer count = userMapper.registerCount(date);
        return count;
    }

    @Override
    public Integer loginCount(String date) {
        Integer count = userMapper.loginCount(date);
        return count;
    }
}
